<?php
/**
 * 项目控制器
 * User: guojing
 * Date: 2020/4/6
 * Time: 20:11
 */
namespace app\api\controller;


use app\api\model\ProjectLogCheckdetail;
use app\api\model\UserMoneyLog;
use app\common\controller\Api;
use app\api\model\Project as ProjectModel;
use app\api\model\ProjectAssign;
use think\Db;
use app\api\model\Category;
use app\api\model\Company as CompanyModel;
use app\api\model\User as UserModel;
use think\Exception;
use app\api\model\ProjectLog;
use think\Log;

class Project extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    /**
     * b端项目列表
     */
    public function index()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('page_size', 10);
        $params = [
            'page' => $page,
            'page_size' => $pageSize
        ];
        if ($userId > 0) {  //已登录
            $params['puid'] = $userId;
        }
        $list = ProjectModel::dataList($params);
        $res = [
            'list' => $list ? $list : [],
            'has_more' => count($list) >= $pageSize ? 1 : 0
        ];
        $this->success('success', $res);
    }

    /**
     * c端项目列表
     */
    public function cindex()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('page_size', 10);
        $params = [
            'page' => $page,
            'page_size' => $pageSize
        ];
        if ($userId > 0) {  //已登录
            $params['uid'] = $userId;
            $list = ProjectModel::cdataList($params);
        } else {    //未登录
            $list = ProjectAssign::dataList($params);
        }

        $res = [
            'list' => $list ? $list : [],
            'has_more' => count($list) >= $pageSize ? 1 : 0
        ];
        $this->success('success', $res);
    }

    /**
     * 项目发布
     */
    public function publish()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        //test
        //$userId = 1;
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }

        //获取用户的企业信息
        $company = CompanyModel::findInfoByCondition(['user_id' => $userId]);
        if (!$company || $company['requesting'] != 2) {
            $this->error(__('企业未认证通过，无法发布'));
        }
        $posts = $this->request->post();

        //项目名称
        $pname = $this->request->post('pname', '');
        // 项目行业
        $pstate = $this->request->post('pstate');
        //项目开始日期
        $startdate = $this->request->post('startdate', 0);
        if ($startdate) {
            $startdate = date('Y-m-d', $startdate);
        } else {
            $startdate = '0000-00-00';
        }
        //上线使用日期
        $usedate = $this->request->post('enddate', 0);
        if ($usedate) {
            $usedate = date('Y-m-d', $usedate);
        } else {
            $usedate = '0000-00-00';
        }
        //需求描述
        $pcontent = $this->request->post('pcontent');
        //项目预算
        $computation = $this->request->post('computation');
        //项目联系人
        $contactname = $this->request->post('contactname');
        //项目联系电话
        $pmobile = $this->request->post('pmobile');

        //人才需求
        $categoryIds = isset($posts['category_ids']) && $posts['category_ids'] && is_array($posts['category_ids']) ? implode(',', $posts['category_ids']) : '';

        if (!$pname) {
            $this->error(__('项目名称为必要信息，不能留空！'));
        }
        if ($pstate == null) {
            $this->error(__('请选择项目行业'));
        }
        if (!$pcontent) {
            $this->error(__('需求描述为必要信息，不能留空！'));
        }
        if (!$contactname) {
            $this->error(__('项目联系人为必要信息，不能留空！'));
        }
        if (!$pmobile) {
            $this->error(__('联系电话为必要信息，不能留空！'));
        }
        /*if (!$categoryIds) {
            $this->error(__('请选择人才需求！'));
        }*/

        Db::startTrans();
        try {
            $data = [
                'pname' => $pname,
                'startdate' => $startdate,
                'pcontent' => $pcontent,
                'category_ids' => $categoryIds,
                'enddate' => $usedate,
                'usedate' => $usedate,
                'computation' => $computation ? $computation : 0,
                'contactname' => $contactname,
                'pmobile' => $pmobile,
                'puid' => $userId,
                'pstate' => $pstate
            ];
            $project = ProjectModel::addRecord($data);
            if (!$project) {
                Db::rollback();
                $this->error(__('发布失败'));
            }

            //对应企业的项目总数增加1
            CompanyModel::incProjectNums(['user_id' => $userId]);

            //增加人才列表待分配记录
            if ($project['id'] && $categoryIds) {
                $categoryIdArr = explode(',', $categoryIds);
                foreach ($categoryIdArr as $categoryId) {
                    $addData = [
                        'project_id' => $project['id'],
                        'category_id' => (int)$categoryId
                    ];
                    ProjectAssign::addRecord($addData);
                }
            }

            Db::commit();

            $this->success('success', []);
        } catch (Exception $exception) {
            Db::rollback();
            $this->error(__('发布失败！'));
        }
    }

    /**
     *  进入发布页面
     */
    public function inpublish()
    {
        // 返回人才列表
        $categoryList = Category::findListByCondition(['type' => 'default']);
        $res = [
            'category_list' => $categoryList ? $categoryList : []
        ];
        $this->success('success', $res);
    }

    /**
     * 获取项目详情
     */
    public function detail()
    {
        $id = $this->request->param('project_id', 0);
        if ($id <= 0) {
            $this->error(__(' 参数错误！'));
        }

        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }

        $user = UserModel::findInfoByCondition(['id' => $userId]);
        if (!$user) {
            $this->error(__('参数错误'));
        }

        $project = ProjectModel::findInfoByCondition(['id' => $id]);
        if (!$project) {
            $this->error(__(' 参数错误！'));
        }

        $publishCompany = CompanyModel::findInfoByCondition(['user_id' => $project['puid']]);
        if (!$publishCompany) {
            $this->error(__('没有对应项目的企业信息！'));
        }

        //获取发布用户的信息
        /*$publisher = UserModel::findInfoByCondition(['id' => $project['puid']]);
        if (!$publisher) {
            $this->error(__('没有对应的发布用户！'));
        }*/

        // 周期
        $cycleDay = (int)((strtotime($project['enddate']) - strtotime($project['startdate'])) / (24 * 3600));
        $cycleDay < 0 && $cycleDay = 0;

        //雇佣信息
        $assign = ProjectAssign::findInfoByCondition(['project_id' => $project['id'], 'uid' => $userId]);
        $hire = [];
        if ($assign) {  //如果有雇佣关系
            $hire = [
                'work_status' => ProjectAssign::getStatusName($assign['work_status']),
                'wage' => $user['wage'],
                'assign_time' => $assign['assign_time'] ? date('Y-m-d', $assign['assign_time']) : '',
                'has_work_hour' => $assign['has_work_hour'] ? (sprintf('%.2f', ($assign['has_work_hour'] / 100))) : 0,
                'uncheck_work_hour' => $assign['uncheck_work_hour'] ? (sprintf('%.2f', ($assign['uncheck_work_hour'] / 100))) : 0,
                'refuse_work_hour' => $assign['refuse_work_hour'] ? (sprintf('%.2f', ($assign['refuse_work_hour'] / 100))) : 0,
                'total_work_hour' => $assign['total_work_hour'] ? (sprintf('%.2f', ($assign['total_work_hour'] / 100))) : 0,
            ];
        }

        //项目账单
        $bill = [
            'pass_price' => 0,
            'uncheck_pass' => 0,
            'refuse_pass' => 0,
            'total_price' => 0
        ];
         if ($assign && $user['wage']) {
             $bill['pass_price'] = sprintf('%.2f', ($user['wage'] * $hire['has_work_hour']));
             $bill['uncheck_pass'] = sprintf('%.2f', ($user['wage'] * $hire['uncheck_work_hour']));
             $bill['refuse_pass'] = sprintf('%.2f', ($user['wage'] * $hire['refuse_work_hour']));
             $bill['total_price'] = sprintf('%.2f', ($bill['pass_price'] + $bill['uncheck_pass']));
         }

        $res = [
            'project' => [
                'id' => $id,
                'pname' => $project['pname'],
                'customer' => $publishCompany['company_name'],
                'contactname' => $project['contactname'],
                'startdate' => $project['startdate'],
                'enddate' => $project['enddate'],
                'cycle_day' => $cycleDay,
                'pcontent' => $project['pcontent'],
                'contact_tel' => $project['pmobile']
            ],
            'hire' => $hire,
            'bill' => $bill
        ];

        $this->success('success', $res);
    }

    /**
     * 获取b端项目详情
     */
    public function bdetail()
    {
        $id = $this->request->param('project_id', 0);
        if ($id <= 0) {
            $this->error(__(' 参数错误！'));
        }

        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }

        $user = UserModel::findInfoByCondition(['id' => $userId]);
        if (!$user) {
            $this->error(__('参数错误'));
        }

        $project = ProjectModel::findInfoByCondition(['id' => $id]);
        if (!$project) {
            $this->error(__(' 参数错误！'));
        }
        if ($project['puid'] != $userId) {
            $this->error(__(' 非法操作！'));
        }

        $publishCompany = CompanyModel::findInfoByCondition(['user_id' => $project['puid']]);
        if (!$publishCompany) {
            $this->error(__('没有对应项目的企业信息！'));
        }

        // 周期
        $cycleDay = (int)((strtotime($project['enddate']) - strtotime($project['startdate'])) / (24 * 3600));
        $cycleDay < 0 && $cycleDay = 0;

        //花费工时
        $spendHours = [];

        //花费费用
        $spendMoneys = [];
        $spendMoneys['pass_price'] = 0;
        $spendMoneys['uncheck_pass'] = 0;
        $spendMoneys['refuse_pass'] = 0;
        $spendMoneys['total_price'] = 0;

        //获取项目分配情况
        $assignList = ProjectAssign::findListByCondition(['project_id' => $project['id']]);
        if ($assignList) {
            foreach ($assignList as $assign) {
                $category = Category::findInfoByCondition(['id' => $assign['category_id']]);
                $user = UserModel::findInfoByCondition(['id' => $assign['uid']]);
                if ($user) {    //如果有用户
                    $assign['has_work_hour'] = ProjectAssign::formatHours($assign['has_work_hour']);
                    $assign['uncheck_work_hour'] = ProjectAssign::formatHours($assign['uncheck_work_hour']);
                    $assign['refuse_work_hour'] = ProjectAssign::formatHours($assign['refuse_work_hour']);

                    $spendHours[] = [
                        'category_name' => $category ? $category['name'] : '',
                        'hours' => $assign['has_work_hour']
                    ];

                    $passPrice = sprintf('%.2f', ($user['wage'] * $assign['has_work_hour']));
                    $uncheckPass = sprintf('%.2f', ($user['wage'] * $assign['uncheck_work_hour']));
                    $refusePass = sprintf('%.2f', ($user['wage'] * $assign['refuse_work_hour']));
                    $totalPrice = sprintf('%.2f', ($passPrice + $uncheckPass));

                    $spendMoneys['pass_price'] += $passPrice;
                    $spendMoneys['uncheck_pass'] += $uncheckPass;
                    $spendMoneys['refuse_pass'] += $refusePass;
                    $spendMoneys['total_price'] += $passPrice;
                }
            }
        }

        $res = [
            'project' => [
                'id' => $id,
                'pname' => $project['pname'],
                'customer' => $publishCompany['company_name'],
                'contactname' => $project['contactname'],
                'startdate' => $project['startdate'],
                'enddate' => $project['enddate'],
                'cycle_day' => $cycleDay,
                'pcontent' => $project['pcontent'],
                'contact_tel' => $project['pmobile'],
                'is_end' => (int)$project['is_end']
            ],
            'spend_hours' => $spendHours,
            'spend_moneys' => $spendMoneys
        ];

        $this->success('success', $res);
    }

    /**
     * 项目日志的添加
     */
    public function addlog()
    {
        try {
            $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
            if ($userId <= 0) {
                $this->error(__('参数错误'));
            }
            $projectId = $this->request->param('project_id', 0);
            $project = [];
            if ($projectId > 0) {
                $project = ProjectModel::findInfoByCondition(['id' => $projectId]);
            }
            if (!$project) {
                $this->error('项目不存在');
            }

            if ($project['is_end'] == 1) {
                $this->error('项目已结束!');
            }

            //获取用户的分配任务记录
            $assign = ProjectAssign::findInfoByCondition(['project_id' => $projectId, 'uid' => $userId]);
            if (!$assign) {
                $this->error('分配任务不存在');
            }

            $posts = $this->request->post();

            //发布时间
            $publisTime = time();

            $timeStart = isset($posts['time_start']) ? intval(trim($posts['time_start'])) : 0;
            if ($timeStart <= 0) {
                $this->error('时段参数错误！');
            }
            $timeEnd = isset($posts['time_end']) ? intval(trim($posts['time_end'])) : 0;
            if ($timeEnd <= 0) {
                $this->error('时段参数错误！');
            }
            if ($timeStart > $timeEnd) {
                $this->error('时段参数错误！');
            }

            //获取该项目提交的最新日志记录
            $newestLog = ProjectLog::getProjectNewestLog(['project_id' => $projectId, 'uid' => $userId]);
            if ($newestLog && $newestLog['time_end'] > $timeStart) {   //本次开始时间小于上次的日志结束时间
                //时间段不能重叠
                $msg = "工时重复提交！您已经提交过".date('H:i', $timeStart)."－".date('H:i', $timeEnd)."的工作日志，请提交其他时段的日志。";
                $this->error($msg);
            }

            $workContent = isset($posts['work_content']) ? trim($posts['work_content']) : '';
            if (!$workContent) {
                $this->error('工作日志为必要信息，不能留空！');
            }

            //明日计划
            $tomorrowPlan = isset($posts['tomorrow_plan']) ? trim($posts['tomorrow_plan']) : '';
            if (!$tomorrowPlan) {
                $this->error('明日计划为必要信息，不能留空！');
            }

            $attachId = isset($posts['attach_id']) ? $posts['attach_id'] : 0;

            $data = [
                'uid' => $userId,
                'project_id' => $projectId,
                'publish_time' => $publisTime,
                'time_start' => $timeStart,
                'time_end' => $timeEnd,
                'work_content' => $workContent,
                'attach_id' => $attachId,
                'tomorrow_plan' => $tomorrowPlan,
                'project_assign_id' => $assign['id']
            ];
            $projectLog = ProjectLog::addRecord($data);
            if (!$projectLog) {
                $this->error(__('添加失败'));
            }

            //更新待工作时长,乘以100保留整数
            $hour = intval(($timeEnd - $timeStart) / 3600 * 100);
            $row = [
                'total_work_hour' => Db::raw("total_work_hour + {$hour}"),
                'uncheck_work_hour' => Db::raw("uncheck_work_hour + {$hour}")
            ];
            ProjectAssign::saveData(['id' => $assign['id']], $row);

            $this->success('success', []);
        } catch (Exception $exception) {
            $this->error(__('添加失败'));
        }
    }

    /**
     * 项目日志列表
     */
    public function logs()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('page_size', 10);
        $projectId = $this->request->param('project_id', 0);

        $project = ProjectModel::findInfoByCondition(['id' => $projectId]);
        if (!$project) {
            $this->success('success', ['list' => [], 'has_more' => 0]);
        }

        $params = [
            'page' => $page,
            'page_size' => $pageSize,
            'project_id' => $projectId
        ];
        if ($userId > 0) {  //已登录
            $params['uid'] = $userId;
        }
        $list = ProjectLog::dataList($params);
        $res = [
            'list' => $list ? $list : [],
            'has_more' => count($list) >= $pageSize ? 1 : 0
        ];
        $this->success('success', $res);
    }

    /**
     * 日志审核
     */
    public function checkLog()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if (!$userId) {
            $this->error('请重新登录', [],401);
        }

        $id = $this->request->param('id', 0, 'intval');
        if ($id <= 0) {
            $this->error(__(' 参数错误！'));
        }
        $status = $this->request->param('status', 0, 'intval');

        //防止接口1s重复调用
        $this->checkApiRequestFrequently("cklog{$id}");

        Db::startTrans();
        try {
            $log = ProjectLog::findInfoByCondition(['id' => $id], 1);
            if (!$log) {
                Db::rollback();
                $this->error(__('参数错误！'));
            }
            if ($log['check_status'] != 0) {
                Db::rollback();
                $this->error(__('不能重复操作！'));
            }

            $project = ProjectModel::findInfoByCondition(['id' => $log['project_id']]);
            if (!$project) {
                Db::rollback();
                $this->error(__('项目不存在！'));
            }
            if ($project['is_end'] == 1) {
                Db::rollback();
                $this->error(__('项目已结束！'));
            }

            $row = [
                'check_status' => $status
            ];
            if ($status == 1) { // 审核通过
                $row['pass_time'] = time();
            } elseif ($status == 2) {   //审核拒绝
                $row['refuse_time'] = time();
            }
            ProjectLog::saveData(['id' => $id], $row);

            unset($row);

            // 工时乘以了100
            $hour = intval(((int)$log['time_end'] - (int)$log['time_start']) / 3600 * 100);

            $assign = ProjectAssign::findInfoByCondition(['id' => $log['project_assign_id'], 'uid' => $log['uid'], 'project_id' => $log['project_id']]);
            if ($assign) {
                if ($status == 1) { // 审核通过
                    // 更新已工作时长
                    $row = [
                        'has_work_hour' => Db::raw("has_work_hour + {$hour}"),
                        'uncheck_work_hour' => Db::raw("uncheck_work_hour - {$hour}")
                    ];
                    ProjectAssign::saveData(['id' => $assign['id']], $row);
                } elseif ($status == 2) {   //审核拒绝
                    // 更新拒绝工作时长
                    $row = [
                        'refuse_work_hour' => Db::raw("refuse_work_hour + {$hour}"),
                        'uncheck_work_hour' => Db::raw("uncheck_work_hour - {$hour}")
                    ];
                    ProjectAssign::saveData(['id' => $assign['id']], $row);
                }
            }

            if ($status == 1) { // 审核通过
                //需要计算价格的工时处理
                $jsHour = ProjectAssign::formatHours($hour);
                if ($jsHour > 0) {  //有工时
                    //查询是否已经给过钱
                    $logCheck = ProjectLogCheckdetail::findInfoByCondition(['project_log_id' => $log['id']]);
                    if ($logCheck) {
                        Db::rollback();
                        $this->error(__('不能重复操作！'));
                    }
                    $reciveUser = UserModel::findInfoByCondition(['id' => $log['uid']], 1);
                    if  (!$reciveUser) {
                        Db::rollback();
                        $this->error(__('日志用户不存在！'));
                    }
                    $amount = ((int)$reciveUser['wage']) * $jsHour;
                    //企业需要扣钱的金额
                    $companyAmunt = $assign['employ_price'] * $jsHour;
                    if ($amount > 0 && $companyAmunt > 0) {  // 有金额
                        $sendUser = UserModel::findInfoByCondition(['id' => $userId], 1);
                        if  (!$sendUser) {
                            Db::rollback();
                            $this->error(__('当前用户不存在！'));
                        }
                        //检测余额是否充足
                        if ($sendUser['money'] < $companyAmunt) {
                            Db::rollback();
                            $this->error(__('余额不足！'));
                        }
                        $logCheckAdd = [
                            'project_log_id' => $log['id'],
                            'project_id' => $log['project_id'],
                            'receive_uid' => $log['uid'],
                            'send_uid' => $userId,
                            'amount' => $companyAmunt,
                            'hours' => $hour,
                            'operate_uid' => $userId
                        ];
                        $logCheckId = ProjectLogCheckdetail::addRecord($logCheckAdd);
                        if (!$logCheckId) {
                            Db::rollback();
                            $this->error(__('审核失败！'));
                        }
                        $userMoneyData = [];
                        if ($assign['is_charge'] == 1) {    //如果项目分配的时候计费
                            // 增加日志用户金额
                            $userData = [
                                'money' => (float)(sprintf('%.2f', $reciveUser['money']) + $amount)
                            ];
                            UserModel::saveData($reciveUser['id'], $userData);
                            //增加金额变动明细
                            $userMoneyData = [
                                'user_id' => $reciveUser['id'],
                                'money' => $amount,
                                'before' => $reciveUser['money'],
                                'after' => $userData['money'],
                                'memo' => "项目[{$log['project_id']}]进账"
                            ];
                            $userMoneyId = UserMoneyLog::addRecord($userMoneyData);
                            if (!$userMoneyId) {
                                Db::rollback();
                                $this->error(__('写入失败！'));
                            }
                        }
                        //减去企业金额
                        if ($sendUser['id'] == $reciveUser['id']) { // 自己给自己操作
                            if (isset($userMoneyData) && $userMoneyData) {
                                $beforeMoney = $userMoneyData['after'];
                                $userData = [
                                    'money' => (float)(sprintf('%.2f', $userMoneyData['after']) - $companyAmunt)
                                ];
                            } else {
                                $beforeMoney = $sendUser['money'];
                                $userData = [
                                    'money' => (float)(sprintf('%.2f', $sendUser['money']) - $companyAmunt)
                                ];
                            }
                            UserModel::saveData($sendUser['id'], $userData);
                            //增加金额变动明细
                            $userMoneyData = [
                                'user_id' => $sendUser['id'],
                                'money' => $companyAmunt,
                                'before' => $beforeMoney,
                                'after' => $userData['money'],
                                'memo' => "项目[{$log['project_id']}]出账"
                            ];
                        } else {
                            $userData = [
                                'money' => (float)(sprintf('%.2f', $sendUser['money']) - $companyAmunt)
                            ];
                            UserModel::saveData($sendUser['id'], $userData);
                            //增加金额变动明细
                            $userMoneyData = [
                                'user_id' => $sendUser['id'],
                                'money' => $companyAmunt,
                                'before' => $sendUser['money'],
                                'after' => $userData['money'],
                                'memo' => "项目[{$log['project_id']}]出账"
                            ];
                        }

                        $userMoneyId = UserMoneyLog::addRecord($userMoneyData);
                        if (!$userMoneyId) {
                            Db::rollback();
                            $this->error(__('写入失败！'));
                        }

                        unset($userMoneyData);
                        unset($userData);
                        unset($logCheckAdd);
                        unset($sendUser);
                    }
                    unset($reciveUser);
                }
            }
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

        $this->success('success', ['check_status' => $status]);
    }

    public function baseinfo()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id <= 0) {
            $this->error(__(' 参数错误！'));
        }
        $res = [];
        //队友
        $res['team_nums'] = ProjectAssign::projectAssignNums($id);
        $this->success('success', $res);
    }

    public function teams()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('page_size', 10);
        $projectId = $this->request->param('id', 0);

        $project = ProjectModel::findInfoByCondition(['id' => $projectId]);
        if (!$project) {
            $this->success('success', ['list' => [], 'has_more' => 0]);
        }

        $params = [
            'page' => $page,
            'page_size' => $pageSize,
            'project_id' => $projectId
        ];
        $list = ProjectAssign::teams($params);
        $res = [
            'list' => $list ? $list : [],
            'has_more' => count($list) >= $pageSize ? 1 : 0
        ];
        $this->success('success', $res);
    }

    /**
     * 结束项目
     */
    public function endProject()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        $projectId = $this->request->param('id', 0, 'intval');
        if ($userId <= 0 || $projectId <= 0) {
            $this->error(__(' 参数错误！'));
        }
        $project = ProjectModel::findInfoByCondition(['id' => $projectId]);
        if (!$project) {
            $this->error(__(' 参数错误！'));
        }
        if ($project['puid'] != $userId) {
            $this->error(__(' 非法操作！'));
        }
        if ($project['spend_progress'] < 100) {
            $this->error(__(' 项目进度为'.$project['spend_progress'].'%,还不能结束！'));
        }

        //结束项目
        Db::startTrans();
        try {
            //项目结束
            ProjectModel::saveData(['id' => $projectId], ['is_end' => 1]);

            // 分配的项目全部变成已完成
            ProjectAssign::saveData(['project_id' => $projectId, 'is_del' => 0, 'work_status' => ['in', [0,1]]], ['work_status' => 2]);

            Db::commit();

            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error(__(' 操作失败！'));
        }
    }

    /**
     * b端项目日志列表
     */
    public function blogs()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('page_size', 10);
        $projectId = $this->request->param('project_id', 0, 'intval');

        $project = ProjectModel::findInfoByCondition(['id' => $projectId]);
        if (!$project) {
            $this->success('success', ['list' => [], 'has_more' => 0]);
        }

        $params = [
            'page' => $page,
            'page_size' => $pageSize,
            'project_id' => $projectId
        ];
        if ($userId > 0) {  //已登录
            $params['uid'] = $userId;
        }
        $list = ProjectLog::bdataList($params);
        $res = [
            'list' => $list ? $list : [],
            'has_more' => count($list) >= $pageSize ? 1 : 0
        ];
        $this->success('success', $res);
    }

    /**
     * b端项目日志详情
     */
    public function blog()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        $logId = $this->request->param('log_id', 0, 'intval');

        if ($userId <= 0) {
            $this->error(__(' 参数错误 ！'));
        }

        $res = [];

        //用户
        $user = UserModel::findInfoByCondition(['id' => $userId]);
        if (!$user) {
            $this->error(__(' 非法操作 ！'));
        }
        $res['hua_name'] = $user['hua_name'];

        $log = ProjectLog::findInfoByCondition(['id' => $logId]);
        if ($log['uid'] != $userId) {
            $this->error(__(' 非法操作 ！'));
        }

        $assign = ProjectAssign::findInfoByCondition(['id' => $log['project_assign_id']]);
        if (!$assign) {
            $this->error(__(' 参数错误 ！'));
        }

        $res['id'] = $logId;

        //岗位
        $category = Category::findInfoByCondition(['id' => $assign['category_id']]);
        $res['category_name'] = $category ? $category['name'] : '';

        // 发布时间
        $res['publish_time'] = date('Y-m-d', $log['publish_time']);

        // 时段
        $res['time_period'] = date('H:i', $log['time_start']) . '-' . date('H:i', $log['time_end']);

        //工时
        $res['work_time'] = (float)(sprintf('%.2f',(($log['time_end'] - $log['time_start']) / 3600)));

        $res['work_content'] = $log['work_content'];
        $res['tomorrow_plan'] = $log['tomorrow_plan'];
        $res['check_status'] = $log['check_status'];

        $this->success('success', $res);
    }

}